﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.InvoiceManagements;
using Reporting.Domain;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.InvoiceManagements;

namespace Reporting.API.Application.CommandHandler.InvoiceManagements
{
    /// <summary>
    /// 添加 开票管理
    /// </summary>
    public class AddInvoiceManagementCommandHandler : IRequestHandler<AddInvoiceManagementCommand, ApiResult>
    {
        private readonly IInvoiceManagementRepository  _invoiceManagementRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddInvoiceManagementCommandHandler> _logger;

        public AddInvoiceManagementCommandHandler(ILogger<AddInvoiceManagementCommandHandler> logger, IMapper mapper, IInvoiceManagementRepository invoiceManagementRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _invoiceManagementRepository = invoiceManagementRepository;
        }

        public async Task<ApiResult> Handle(AddInvoiceManagementCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 将 DTO 映射为实体类
                var userEntity = _mapper.Map<InvoiceManagement>(request);

                // 调用仓储层添加用户
                var addProductionorder = await _invoiceManagementRepository.InsertAsync(userEntity);

                // 返回成功结果  StatusCodeEnum
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加失败");
                throw;
            }
        }
    }
}
